#include "friend.h"
#include "protocol.h"
#include "ui_friend.h"
#include "client.h"

#include <QInputDialog>
#include <QMessageBox>

Friend::Friend(QWidget *parent) : QWidget(parent), ui(new Ui::Friend)
{
    ui->setupUi(this);
    m_pOnlineUser = new OnlineUser;
    m_pChat = new Chat;
    flushFriend();
}

Friend::~Friend()
{
    delete ui;
}

OnlineUser *Friend::getOnlineUser()
{
    return m_pOnlineUser;
}

void Friend::flushFriend()
{
    PDU* pdu = mkPDU(ENUM_MSG_TYPE_FLUSH_FRIEND_REQUEST, 0);
    Client::getInstance().sendMsg(pdu);
}

void Friend::updateFriendWigetList(QStringList &friendlist)
{
    ui->friend_LW->clear();
    ui->friend_LW->addItems(friendlist);
}

void Friend::on_findUser_BP_clicked()
{
    qDebug() << "输入查找用户名";
    QString strName = QInputDialog::getText(this, "查找用户", "用户名:");

    PDU* pdu = mkPDU(ENUM_MSG_TYPE_FIND_USER_REQUEST, 0);
    memcpy(pdu->caData, strName.toStdString().c_str(), 32);
    Client::getInstance().sendMsg(pdu);

}

void Friend::on_onlineUser_BP_clicked()
{
    if(m_pOnlineUser->isHidden())
    {
        m_pOnlineUser->show();
    }
    PDU* pdu = mkPDU(ENUM_MSG_TYPE_ONLINE_USER_REQUEST, 0);
    Client::getInstance().sendMsg(pdu);
}

void Friend::on_flushFriend_BP_clicked()
{
    flushFriend();
}

void Friend::on_delFriend_BP_clicked()
{
    QListWidgetItem* pItem = ui->friend_LW->currentItem();
    if(!pItem){
        QMessageBox::information(this, "删除好友", "请选择要删除的好友");
        return;
    }
    QString strTarName = pItem->text();
    if(QMessageBox::question(this, "删除好友", QString("确认删除%1吗?").arg(strTarName)) == QMessageBox::No) return;
    PDU* pdu = mkPDU(ENUM_MSG_TYPE_DELETE_FRIEND_REQUEST, 0);
    memcpy(pdu->caData, Client::getInstance().m_strLoginName.toStdString().c_str(), 32);
    memcpy(pdu->caData + 32, strTarName.toStdString().c_str(), 32);
    Client::getInstance().sendMsg(pdu);
}

void Friend::on_chat_BP_clicked()
{
    QListWidgetItem* pItem = ui->friend_LW->currentItem();
    if(!pItem){
        QMessageBox::information(this, "聊天", "请选择要聊天的好友");
        return;
    }
    if(m_pChat->isHidden()){
        m_pChat->show();
    }
    m_pChat->setChatName(pItem->text());
}
